import { wechatCpRegisterAPI } from '@/wechat/api'
/**
 * @description: 获取echarts需要的名称信息
 * @param items 包含 type: string, // userType id: string, // openid corpid: string, // corpid (非必须) 的对象数据
 * @return {*}
 */
export async function getWxLoginNames(items) {
  if (WWOpenData.initCanvas) {
    WWOpenData.initCanvas()
  }

  const result = await new Promise((resolve, reject) => {
    WWOpenData.prefetch({ items }, (err, data) => {
      if (err) {
        return reject(err)
      }
      resolve(data)
    })
  })

  var data = []
  result.items.forEach(element => {
    data.push(element.data)
  })

  return data
}
/**
     * @description: 获取登录code
     * @return {*}
     */
export function getLoginCode() {
  if (localStorage.getItem('loginType')) {
    localStorage.removeItem('loginType')
  }

  const urlHash = window.location.href
  console.log('urlHash', urlHash)
  if (urlHash.includes('code') && urlHash.includes('appid')) {
    const arr = urlHash.split('?')[1].split('&')
    // console.log(arr)
    const findRes = arr.find(item => item.startsWith('code='))
    // console.log(findRes)
    if (!findRes) {
      return null
    } else {
      return {
        loginType: 4, // 扫码登录,
        cpCode: findRes.replace('code=', '')
      }
    }
  } else if (urlHash.includes('code') && urlHash.includes('appid') && urlHash.includes('state')) {
    const arr = urlHash.split('?')[1].split('&')
    let findRes = arr.find(item => item.startsWith('state='))
    const state = findRes ? findRes.replace('state=', '') : null
    findRes = arr.find(item => item.startsWith('code='))
    if (!findRes || state !== 'WX_AUTH_LOGIN') {
      return null
    } else {
      localStorage.setItem('loginType', 4)
      return {
        loginType: 4, // 企业微信内登录,
        cpCode: findRes.replace('code=', '')
      }
    }
  } else if (urlHash.includes('auth_code') && urlHash.includes('state')) {
    const arr = urlHash.split('?')[1].split('&')
    const stateFindRes = arr.find(item => item.startsWith('state='))
    const stateValue = stateFindRes ? stateFindRes.replace('state=', '') : null
    const findRes = arr.find(item => item.startsWith('auth_code='))
    const authCode = findRes.replace('auth_code=', '')
    wechatCpRegisterAPI({
      authCode: authCode
    }).then((res) => {
      if (stateValue == 'install') {
        window.location.href = 'https://www.5kcrm.com/wechatcrm'
      }
    })
    return true
  }

  return null
}
